import Icon from '@/components/Icon';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { Toast } from 'antd-mobile';
import { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import io, { Socket } from 'socket.io-client';
import { getToken } from '@/utils/storage';

type Message = {
  type?: 'robot' | 'user';
  msg: string;
  timestamp: number;
};

export default function ProfileChat() {
  // 用于缓存socket.io客户端实例
  const clientRef = useRef<Socket | null>(null);

  const [msg, setMsg] = useState('');

  const [list, setList] = useState<Message[]>([
    {
      type: 'robot',
      msg: '亲爱的用户您好，小智同学为您服务。',
      timestamp: Date.now(),
    },
    { type: 'user', msg: '你好啊。', timestamp: Date.now() + 1 },
  ]);

  // 点击发送
  const handleSend = () => {
    if (!msg) return Toast.show({ content: '请输入内容.' });
    const userMsg: Message = {
      type: 'user',
      msg: msg,
      timestamp: Date.now(),
    };

    // 用户消息
    setList([...list, userMsg]);
    // 清空输入框
    setMsg('');
  };

  useEffect(() => {
    const client = io('http://toutiao.itheima.net', {
      transports: ['websocket'],
      //  在查询字符串中传递token
      query: {
        token: getToken().token,
      },
    });
    // 监听连接成功的事件
    client.on('connect', () => {
      // 向聊天记录中添加一条消息
      setList([
        ...list,
        { type: 'robot', msg: '我现在恭候着您的提问。', timestamp: Date.now() },
      ]);
    });

    //  监听收到消息的事件
    client.on('message', (data) => {
      console.log('>>>>收到 socket.io 消息:', data);
      console.log(66, list);

      // 修改list使用箭头函数和不使用箭头函数的区别:不使用箭头i函数,调用多个setState,后面的会覆盖前面的(参考:reac-day-4-问题点)
      setList((list) => [
        ...list,
        { type: 'robot', msg: data.msg, timestamp: Date.now() },
      ]);
    });

    // 将客户端实例缓存到ref引用中
    clientRef.current = client;

    // 在组建销毁时关闭socket.io的连接
    return () => {
      client.close();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 列表数据有变化，滚动到 body 底部
  useEffect(() => {
    console.log(86, list);

    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: 'smooth',
    });
  }, [list]);

  // 按回车发消息
  const onSendMessage = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      clientRef.current?.emit('message', {
        msg: msg,
        timestamp: Date.now(),
      });
      setList([...list, { type: 'user', msg: msg, timestamp: Date.now() + 1 }]);

      // 清空输入框
      setMsg('');
    }
  };
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>小智同学</NavBar>

      {/* 聊天记录列表 - 开始 */}
      <div className="chat-list">
        {list.map((item) => {
          if (item.type === 'robot') {
            return (
              <div className="chat-item robot" key={item.timestamp}>
                <Icon type="iconbtn_xiaozhitongxue" />
                <div className="message">{item.msg}</div>
              </div>
            );
          } else {
            return (
              <div className="chat-item user" key={item.timestamp}>
                <img
                  src={'http://toutiao.itheima.net/images/user_head.jpg'}
                  alt=""
                />
                <div className="message">{item.msg}</div>
              </div>
            );
          }
        })}
      </div>
      {/* 聊天记录列表 - 结束 */}

      {/* 底部消息输入框 */}
      <div className="footer">
        <div className="input-footer">
          <Icon type="iconbianji" />
          <Input
            onKeyDown={(e) => onSendMessage(e)}
            autoFocus
            className="no-border"
            placeholder="请描述您的问题"
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
          />
          <span className="send" onClick={handleSend}>
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
